package top100.backtrack;

import java.util.*;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/16 12:20
 * @description: 给定一个候选人编号的集合 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。
 * <p>
 * candidates 中的每个数字在每个组合中只能使用 一次 。
 * <p>
 * 注意：解集不能包含重复的组合。
 * <p>
 * <p>
 * <p>
 * 示例 1:
 * <p>
 * 输入: candidates = [10,1,2,7,6,1,5], target = 8,
 * 输出:
 * [
 * [1,1,6],
 * [1,2,5],
 * [1,7],
 * [2,6]
 * ]
 * 示例 2:
 * <p>
 * 输入: candidates = [2,5,2,1,2], target = 5,
 * 输出:
 * [
 * [1,2,2],
 * [5]
 * ]
 * <p>
 * <p>
 * 提示:
 * <p>
 * 1 <= candidates.length <= 100
 * 1 <= candidates[i] <= 50
 * 1 <= target <= 30
 */
public class Solution40 {
    public void backtrack(int[] candidates, int start, int target, LinkedList<Integer> path, List<List<Integer>> res, Set<String> set) {
        if (target == 0) {
            if (!set.contains(path.toString())) {
                set.add(path.toString());
                res.add(new ArrayList<>(path));
            }
            return;
        }
        if (target < 0) {
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            if(i > start && candidates[i] == candidates[i - 1])
                continue;
            path.add(candidates[i]);
            backtrack(candidates, i + 1, target - candidates[i], path, res, set);
            path.removeLast();
        }
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(candidates, 0, target, new LinkedList<>(), res, new HashSet<>());
        return res;
    }

    public static void main(String[] args) {
        Solution40 s = new Solution40();
        int[] candidates = {10, 1, 2, 7, 6, 1, 5};
        int target = 8;
        List<List<Integer>> res = s.combinationSum2(candidates, target);
        System.out.println(res);
    }

}
